package cn.ztq.test0614.ui.home;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cn.ztq.test0614.R;

import cn.ztq.test0614.receiver.BluetoothReceiver;
import cn.ztq.test0614.receiver.ScanListener;

public class HomeFragment extends Fragment implements View.OnClickListener, ScanListener {

//    private FragmentHomeBinding binding;
    private RVDeviceAdapter rvDeviceAdapter;

    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View inflate = LayoutInflater.from(getContext()).inflate(R.layout.fragment_home, container, false);



        Button button = inflate.findViewById(R.id.button);
        Button button2 = inflate.findViewById(R.id.button2);
        RecyclerView recyclerView = inflate.findViewById(R.id.recycler_view);
        rvDeviceAdapter = new RVDeviceAdapter();
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setAdapter(rvDeviceAdapter);
        button.setOnClickListener(this);
        button2.setOnClickListener(this);

        return inflate;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
//        binding = null;
    }


    private BluetoothManager bluetoothManager;
    private BluetoothAdapter adapter;
    private BluetoothLeScanner scanner;

    private ScanCallback callback;
    private String strName = "";


    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.button) {
//            startBleScan();
            scanBluetooth();
        } else if (v.getId() == R.id.button2) {
            scanner.stopScan(callback);
        }


    }


    private void scanBluetooth() {
        BluetoothAdapter defaultAdapter = BluetoothAdapter.getDefaultAdapter();
        defaultAdapter.startDiscovery();
        IntentFilter iFilter = new IntentFilter(
                BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        iFilter.addAction(BluetoothDevice.ACTION_FOUND);
        iFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        getActivity().registerReceiver(new BluetoothReceiver(this), iFilter);
    }

    @Override
    public void iScan(Map<String, BluetoothDevice> map) {
        List<BluetoothDevice> collect = new ArrayList<>(map.values());
        rvDeviceAdapter.setList(collect);
    }
}